/*
 * Copyright (c) 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.libermundi.tapestry.ckeditor.mixins;

import java.util.Map;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Path;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.corelib.components.TextArea;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.javascript.JavaScriptSupport;
import org.libermundi.tapestry.ckeditor.CKEditorContants;

import com.google.common.base.Strings;

/**
 * A mixin that replaces a {@link TextArea} component with a CKEditor instance. The initial value in
 * the ckeditor will be the textarea value.
 * 
 * @tapestrydoc
 */
public class CKEditor {
	/**
	 * The specific configurations to apply to this editor instance. Configurations set here will
	 * override global CKEditor settings.
	 * <p>
	 * See the <a href="http://docs.cksource.com/ckeditor_api/index.html">ckeditor documentation</a>
	 * for more details.
	 */
	@Parameter
	private Map<String, ?> _parameters;

	@InjectContainer
	private TextArea _textArea;

	@Inject
	private JavaScriptSupport _javaScriptSupport;
	
	@Inject
	@Symbol(CKEditorContants.SYMBOL_FILEBROWSER_URL)
	private String _fileBrowser;
	
	@Inject
	@Path("${ckeditor.library_v3}/ckeditor.js")
	private Asset _ckeditor3;
	
	@Inject
	@Path("${ckeditor.library_v4}/ckeditor.js")
	private Asset _ckeditor4;
	
	@Inject
	@Path("${ckeditor.assets}/js/init-ckeditor.js")
	private Asset _ckInit;
	
	@Inject
	@Symbol(CKEditorContants.SYMBOL_CKEDITOR_VERSION)
	private String _version;

	@Inject
	@Path("${ckeditor.symbols.smileydir}")
	private Asset _smileyPath;
	
	@Inject
	@Path("${ckeditor.symbols.customconfig}")
	private Asset _customConfig;
	
	@Inject
	private Request _request;
	
	@SetupRender
	public void setupRender(){
		if(_version.equals("default")){
			_javaScriptSupport.importJavaScriptLibrary(_ckeditor3);
		} else {
			_javaScriptSupport.importJavaScriptLibrary(_ckeditor4);
		}
		_javaScriptSupport.importJavaScriptLibrary(_ckInit);
	}

	@AfterRender
	void afterRender(MarkupWriter writer) {
		String id = _textArea.getClientId();

		JSONObject json = new JSONObject();
		if(_smileyPath != null && _smileyPath.getResource().exists()){
			String smileyUrl = _smileyPath.toClientURL();
			json.put("smiley_path", smileyUrl  + (smileyUrl.endsWith("/") ? "" : "/"));
		}
		
		if(_customConfig != null && _customConfig.getResource().exists()){
			json.put("customConfig", _customConfig.toClientURL());
		}
		
		if(!Strings.isNullOrEmpty(_fileBrowser)){
			json.put("filebrowserBrowseUrl",_request.getContextPath() + _fileBrowser);
		}
		
		if (_parameters != null)
			for (String paramName : _parameters.keySet())
				json.put(paramName, _parameters.get(paramName));
		_javaScriptSupport.addInitializerCall("initCKEditor", new JSONArray(id, json));
	}
}
